package com.ledim.activity;

import android.annotation.TargetApi;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.ledim.activity.base.LeDimBaseActivity;
import com.ledim.adapter.SearchPagerAdapter;
import com.ledim.bean.ChatRoomBean;
import com.ledim.bean.LedimChannelBean;
import com.ledim.bean.LedimSearchRecord;
import com.ledim.bean.SearchResultResponse;
import com.ledim.datastatistics.LeDimAnalysisUtils;
import com.ledim.db.LedimDBManager;
import com.ledim.itf.LedimSearchInterface;
import com.ledim.ledimview.SearchBarView;
import com.ledim.ledimview.ViewPagerSearchListView;
import com.ledim.service.LedimApiServiceUtils;
import com.ledim.service.LedimHttpObserver;
import com.ledim.utils.LedimNetWorkUtils;
import com.ledim.utils.ToastUtil;
import com.letv.android.young.client.R;
import com.letv.tracker2.enums.EventType;
import com.letv.tracker2.enums.Key;
import java.util.ArrayList;
import java.util.HashMap;

/**
 * 搜索结果页
 */
public class SearchResultActivity extends LeDimBaseActivity implements LedimSearchInterface {

    public static final String KEYWORD = "keyword";
    public static final String ADD_PLAY = "add_play";
    public static final String ROOM_ID = "room_id";
    private View mTabsLayout;
    private View mNoSearchLayout;
    private View mNoNetLayout;
    private View mWorkLayout;
    private View mAllResultLayout;
    private View mNoDataLayout;
    private TextView mDataRefresh;
    private TextView mReload;
    private SearchBarView mSearchView;
    private ImageView mCancel;
    private String mKey;
    private LinearLayout mTabView;
    private HorizontalScrollView mScroll;
    private ViewPager mViewPager;
    private SearchPagerAdapter mPagerAdapter;
    private int mTabWidth;
    private boolean mAddPlay;
    private String mRoomId;

    private TextView mAddTitle;
    private TextView mAddFinish;
    private ArrayList<LedimChannelBean> mChannels = new ArrayList<LedimChannelBean>();
    private ArrayList<TextView> mTextViewList = new ArrayList<TextView>();
    private ArrayList<View> mLineViewList = new ArrayList<View>();
    private ArrayList<ViewPagerSearchListView> mViewPagerList =
            new ArrayList<ViewPagerSearchListView>();
    private SearchResultResponse resultResponse;

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_search_result;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mAddPlay) {
            //从放映厅里面过来的
            reportSearchExpose(LeDimAnalysisUtils.ROOM_SEARCH_CODE, "roomSearchResult");
        } else {
            //直接搜索的
            reportSearchExpose(LeDimAnalysisUtils.ALBUM_SEARCH_CODE, "searchResult");
        }
    }

    /**
     * 上报搜索页面曝光
     *
     * @param str
     */
    private void reportSearchExpose(String widgetId, String str) {
        HashMap<String, String> params = new HashMap<String, String>();
        params.put(Key.Type.name(), str);
        LeDimAnalysisUtils.reportEvent(widgetId, EventType.Expose, params);
    }

    private void initView() {
        mKey = getIntent().getStringExtra(KEYWORD);
        mAddPlay = getIntent().getBooleanExtra(ADD_PLAY, false);
        ChatRoomBean mRoom = (ChatRoomBean) getIntent().getSerializableExtra(ROOM_ID);
        if (mRoom != null) {
            mRoomId = mRoom.roomId;
        }
        mTabView = (LinearLayout) findViewById(R.id.channels_tab_view);
        mScroll = (HorizontalScrollView) findViewById(R.id.channels_tab_scroll);
        mViewPager = (ViewPager) findViewById(R.id.category_viewpager);
        mCancel = (ImageView) findViewById(R.id.search_cancel);
        mTabsLayout = findViewById(R.id.search_result_header_bar);
        mNoNetLayout = findViewById(R.id.no_network);
        mNoSearchLayout = findViewById(R.id.no_search);
        mWorkLayout = findViewById(R.id.work_layout);
        mNoDataLayout = findViewById(R.id.no_data);
        mAllResultLayout = findViewById(R.id.search_result_work_layout);
        mDataRefresh = (TextView) findViewById(R.id.data_refresh);
        mReload = (TextView) findViewById(R.id.not_network_reload);
        mAddTitle = (TextView) findViewById(R.id.add_title);
        mAddFinish = (TextView) findViewById(R.id.add_finish);
        mSearchView = (SearchBarView) findViewById(R.id.search_view);

        mCancel.setOnClickListener(this);
        mReload.setOnClickListener(this);
        mAddFinish.setOnClickListener(this);
        mDataRefresh.setOnClickListener(this);
        mAllResultLayout.setVisibility(View.VISIBLE);

        if (mAddPlay) {
            mAddTitle.setText("添加到放映单");
            mAddFinish.setVisibility(View.VISIBLE);
        } else {
            mAddTitle.setText("搜索");
            mAddFinish.setVisibility(View.GONE);
        }
        mSearchView.bindData(mKey, this);

        if (LedimNetWorkUtils.isNetworkAvailable(this)) {
            mWorkLayout.setVisibility(View.VISIBLE);
            mNoNetLayout.setVisibility(View.GONE);
            if (mAddPlay) {
                //从放映厅过来的
                LedimApiServiceUtils.getSearchResult(null, mKey, 1, 2, observer);
            } else {
                //直接搜索的
                LedimApiServiceUtils.getSearchResult(null, mKey, 1, 1, observer);
            }
        } else {
            ToastUtil.toast("网络错误");
            mWorkLayout.setVisibility(View.GONE);
            mNoNetLayout.setVisibility(View.VISIBLE);
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.search_cancel:
                finish();
                break;
            case R.id.add_finish:
                //关闭页面
                setResult(-1);
                finish();
                break;
            case R.id.not_network_reload:
                if (LedimNetWorkUtils.isNetworkAvailable(this)) {
                    mWorkLayout.setVisibility(View.VISIBLE);
                    mNoNetLayout.setVisibility(View.GONE);
                    if (mAddPlay) {
                        LedimApiServiceUtils.getSearchResult(null, mKey, 1, 2, observer);
                    } else {
                        LedimApiServiceUtils.getSearchResult(null, mKey, 1, 1, observer);
                    }
                } else {
                    ToastUtil.toast("网络错误");
                    mWorkLayout.setVisibility(View.GONE);
                    mNoNetLayout.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.data_refresh:
                if (mAddPlay) {
                    LedimApiServiceUtils.getSearchResult(null, mKey, 1, 2, observer);
                } else {
                    LedimApiServiceUtils.getSearchResult(null, mKey, 1, 1, observer);
                }
                break;
        }
    }

    private LedimHttpObserver<SearchResultResponse> observer =
            new LedimHttpObserver<SearchResultResponse>() {
                @Override
                public void onError(Throwable e) {
                    super.onError(e);
                }

                @Override
                public void onNext(SearchResultResponse response) {
                    super.onNext(response);
                    resultResponse = response;
                    mSearchView.setListViewSuggestedGone();
                    mAllResultLayout.setVisibility(View.VISIBLE);
                    if (response != null) {
                        mWorkLayout.setBackgroundColor(Color.parseColor("#ffffff"));
                        mNoDataLayout.setVisibility(View.GONE);
                        if (response.success) {
                            if (response.data.related.size() == 0 &&
                                    response.data.data.size() == 0) {
                                mTabsLayout.setVisibility(View.GONE);
                                mNoSearchLayout.setVisibility(View.VISIBLE);
                            } else {
                                mNoSearchLayout.setVisibility(View.GONE);
                                mTabsLayout.setVisibility(View.VISIBLE);
                                mChannels.clear();
                                mChannels.add(new LedimChannelBean("全部"));
                                mChannels.addAll(response.data.channels);
                                initTabView();
                            }
                        }
                    } else {
                        mWorkLayout.setBackgroundColor(Color.parseColor("#F3F3F3"));
                        mNoDataLayout.setVisibility(View.VISIBLE);
                    }
                }
            };

    private void doRefreshSearchResult(String msg) {
        //请求数据
        mTabsLayout.setVisibility(View.GONE);
        mViewPager.setVisibility(View.GONE);
        mViewPager.setAdapter(null);//数据为空的操作
        mKey = msg;
        if (LedimNetWorkUtils.isNetworkAvailable(this)) {
            mWorkLayout.setVisibility(View.VISIBLE);
            mNoNetLayout.setVisibility(View.GONE);
            if (mAddPlay) {
                //从放映厅过来的
                LedimApiServiceUtils.getSearchResult(null, mKey, 1, 2, observer);
            } else {
                //直接搜索的
                LedimApiServiceUtils.getSearchResult(null, mKey, 1, 1, observer);
            }
        } else {
            ToastUtil.toast("网络错误");
            mWorkLayout.setVisibility(View.GONE);
            mNoNetLayout.setVisibility(View.VISIBLE);
        }
        LedimSearchRecord record = new LedimSearchRecord();
        record.keyword = msg;
        record.time = System.currentTimeMillis();
        LedimDBManager.getInstance().getDaoSession().getLedimSearchRecordDao().insert(record);
    }

    /**
     * 初始化标题
     */
    private void initTabView() {
        DisplayMetrics dm = getResources().getDisplayMetrics();
        if (mChannels.size() >= 5) {
            mTabWidth = dm.widthPixels / 5;
        } else {
            mTabWidth = dm.widthPixels / mChannels.size();
        }
        mTabView.removeAllViews();
        mTextViewList.clear();
        mLineViewList.clear();

        for (int i = 0; i < mChannels.size(); i++) {
            mTabView.addView(addTabView(mChannels.get(i).name, i));
        }

        mTextViewList.get(0).setTextColor(getResources().getColor(R.color.text_color_level2));
        mLineViewList.get(0).setVisibility(View.VISIBLE);
        initViewPager();
    }

    /**
     * 初始化viewpager
     */
    private void initViewPager() {
        mViewPagerList.clear();
        mPagerAdapter = null;
        LayoutInflater inflater = LayoutInflater.from(this);
        for (int i = 0; i < mChannels.size(); i++) {
            ViewPagerSearchListView view =
                    (ViewPagerSearchListView) inflater.inflate(R.layout.tab_viewpager_list, null);
            view.mIsReload = false;
            mViewPagerList.add(view);
        }

        mViewPagerList.get(0)
                      .bindData(resultResponse.data.data, resultResponse.data.related, mChannels.get(0).id, mKey, mRoomId, true);
        mViewPager.setVisibility(View.VISIBLE);

        if (mPagerAdapter == null) {
            mPagerAdapter = new SearchPagerAdapter(this, mViewPagerList);
            mViewPager.setAdapter(mPagerAdapter);
        } else {
            mPagerAdapter.list = mViewPagerList;
            mPagerAdapter.notifyDataSetChanged();
        }

        mViewPager.setCurrentItem(0);
        mScroll.smoothScrollTo(mTabWidth * (-2), 0);
        mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int position) {
                for (int j = 0; j < mTextViewList.size(); j++) {
                    TextView textView = mTextViewList.get(j);
                    textView.setTextColor(getResources().getColor(R.color.text_color_level5));
                    View view = mLineViewList.get(j);
                    view.setBackgroundColor(getResources().getColor(R.color.yellow));
                    view.setVisibility(View.INVISIBLE);
                }
                mTextViewList.get(position)
                             .setTextColor(getResources().getColor(R.color.text_color_level2));
                mLineViewList.get(position).setVisibility(View.VISIBLE);
                mViewPagerList.get(position).setVisibility(View.VISIBLE);
                mScroll.smoothScrollTo(mTabWidth * (position - 2), 0);
                if (!mViewPagerList.get(position).mIsReload) {
                    mViewPagerList.get(position)
                                  .bindData(resultResponse.data.data, resultResponse.data.related, mChannels
                                          .get(position).id, mKey, mRoomId, true);
                }
            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });

    }

    /**
     * 添加标题
     */
    private View addTabView(String name, final int position) {
        View view = getLayoutInflater().inflate(R.layout.tab_item, null);
        View layout = view.findViewById(R.id.tab_item_layout);
        TextView textView = (TextView) view.findViewById(R.id.tab_item_name);
        View lineView = view.findViewById(R.id.tab_item_line);
        textView.setText(name);
        mTextViewList.add(position, textView);
        mLineViewList.add(position, lineView);

        layout.setOnClickListener(new View.OnClickListener() {
            @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
            @Override
            public void onClick(View v) {
                mViewPager.setCurrentItem(position);
                for (int j = 0; j < mTextViewList.size(); j++) {
                    TextView textView = mTextViewList.get(j);
                    textView.setTextColor(getResources().getColor(R.color.text_color_level5));
                    View view = mLineViewList.get(j);
                    view.setBackgroundColor(getResources().getColor(R.color.yellow));
                    view.setVisibility(View.INVISIBLE);
                }
                mTextViewList.get(position)
                             .setTextColor(getResources().getColor(R.color.text_color_level2));
                mLineViewList.get(position).setVisibility(View.VISIBLE);
            }
        });
        return view;
    }

    @Override
    public void notifyViewVisible(int visible) {
        mAllResultLayout.setVisibility(visible);
    }

    @Override
    public void doSearch(String word) {
        mSearchView.setSearchKey(word);
        doRefreshSearchResult(word);
    }

    @Override
    public boolean autoShowKeyBoard() {
        return false;
    }

}
